// 初始化流程图
let svg, width, height;
let simulation;

function initFlowchart() {
    const container = document.getElementById('flowchart');
    width = container.clientWidth;
    height = container.clientHeight;

    // 清除现有内容
    d3.select("#flowchart").selectAll("*").remove();

    svg = d3.select("#flowchart")
        .append("svg")
        .attr("width", width)
        .attr("height", height);

    // 添加箭头标记
    svg.append("defs").append("marker")
        .attr("id", "arrowhead")
        .attr("viewBox", "0 -5 10 10")
        .attr("refX", 15)
        .attr("refY", 0)
        .attr("markerWidth", 6)
        .attr("markerHeight", 6)
        .attr("orient", "auto")
        .append("path")
        .attr("d", "M0,-5L10,0L0,5")
        .attr("fill", "#9ca3af");

    // 创建缩放行为
    const zoom = d3.zoom()
        .scaleExtent([0.5, 3])
        .on("zoom", (event) => {
            g.attr("transform", event.transform);
        });

    svg.call(zoom);

    const g = svg.append("g");

    // 绘制连接线
    const links = g.selectAll(".link")
        .data(flowchartData.links)
        .enter().append("line")
        .attr("class", "link")
        .attr("x1", d => getNodeById(d.source).x)
        .attr("y1", d => getNodeById(d.source).y)
        .attr("x2", d => getNodeById(d.target).x)
        .attr("y2", d => getNodeById(d.target).y);

    // 绘制节点
    const nodes = g.selectAll(".node")
        .data(flowchartData.nodes)
        .enter().append("g")
        .attr("class", d => `node ${d.type}`)
        .attr("transform", d => `translate(${d.x}, ${d.y})`)
        .on("click", handleNodeClick);

    // 添加节点矩形
    nodes.append("rect")
        .attr("width", d => getNodeWidth(d))
        .attr("height", d => getNodeHeight(d))
        .attr("x", d => -getNodeWidth(d) / 2)
        .attr("y", d => -getNodeHeight(d) / 2);

    // 添加节点文本
    nodes.append("text")
        .attr("dy", 0)
        .text(d => d.label)
        .each(function(d) {
            const text = d3.select(this);
            const lines = d.label.split('\n');
            text.text('');
            lines.forEach((line, i) => {
                text.append("tspan")
                    .attr("x", 0)
                    .attr("dy", i === 0 ? 0 : "1.2em")
                    .text(line);
            });
        });

    // 初始居中
    const initialTransform = d3.zoomIdentity
        .translate(width/2 - 400, height/2 - 150)
        .scale(0.8);
    
    svg.call(zoom.transform, initialTransform);
}

function getNodeById(id) {
    return flowchartData.nodes.find(node => node.id === id);
}

function getNodeWidth(node) {
    if (node.type === "root") return 200;
    if (node.type === "driver") return 140;
    return 120;
}

function getNodeHeight(node) {
    if (node.type === "root") return 60;
    if (node.type === "driver") return 50;
    return 40;
}

function handleNodeClick(event, d) {
    if (d.type === "subtype" && caseStudies[d.id]) {
        showDetailCard(d.id);
    }
}

function showDetailCard(nodeId) {
    const card = document.getElementById('detail-card');
    const content = document.getElementById('detail-content');
    const data = caseStudies[nodeId];

    if (!data) return;

    content.innerHTML = `
        <h4 class="text-lg font-semibold mb-2">${data.title}</h4>
        <p class="text-gray-600 mb-4">${data.description}</p>
        
        <h5 class="font-medium mb-2">关键指标</h5>
        <div class="metrics">
            ${Object.entries(data.metrics).map(([key, value]) => `
                <div class="metric-item">
                    <div class="metric-value">${value}</div>
                    <div class="metric-label">${key}</div>
                </div>
            `).join('')}
        </div>
        
        <h5 class="font-medium mb-2">核心政策</h5>
        <ul class="list-disc list-inside">
            ${data.policies.map(policy => `<li>${policy}</li>`).join('')}
        </ul>
    `;

    card.classList.remove('hidden');
    card.classList.add('fade-in');
}

function simulatePath() {
    const geo = document.getElementById('geo-select').value;
    const system = document.getElementById('system-select').value;
    const industry = document.getElementById('industry-select').value;
    const culture = document.getElementById('culture-select').value;
    const security = document.getElementById('security-select').value;

    const path = [geo, system, industry, culture, security].filter(Boolean).join('-');

    if (path === '') {
        alert('请至少选择一个选项');
        return;
    }

    const result = simulationResults[path] || {
        title: "自定义模式",
        description: "基于您选择的组合，形成独特的空域管理模式",
        features: ["需要进一步分析", "建议咨询专家", "考虑本土化适配"]
    };

    const card = document.getElementById('detail-card');
    const content = document.getElementById('detail-content');

    content.innerHTML = `
        <div class="simulation-result">
            <h4 class="text-lg font-semibold mb-2">${result.title}</h4>
            <p class="mb-4">${result.description}</p>
            <div class="simulation-features">
                ${result.features.map(feature => 
                    `<span class="feature-tag">${feature}</span>`
                ).join('')}
            </div>
        </div>
    `;

    card.classList.remove('hidden');
    card.classList.add('fade-in');
}

// 响应式处理
function handleResize() {
    initFlowchart();
}

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initFlowchart();
    window.addEventListener('resize', handleResize);
});

// 触摸设备支持
let touchTimeout;
document.addEventListener('touchstart', function() {
    if (touchTimeout) clearTimeout(touchTimeout);
    touchTimeout = setTimeout(() => {
        // 触摸设备上的长按处理
    }, 500);
});
